package com.dls.admin.controller;

import com.dls.admin.model.Goods;
import com.dls.admin.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Controller
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    /**
     * 货物管理页面分页查询
     *
     * @return
     */
    @RequestMapping("/goods")
    public String goods(Goods goods, PageInfo page, Model m) {
        // 将查询的数据以分页的形式展示
        PageHelper.startPage(page.getPageNum(), 5, "id desc");// 还可以指定排序规则
        List<Goods> list = goodsService.findGoodsList(goods);
        PageInfo<Goods> pageResults = new PageInfo<>(list);
        m.addAttribute("page", pageResults);
        m.addAttribute("msg", goods.getMsg());
        return "goods";
    }

    /**
     * 新增页面跳转
     *
     * @return
     */
    @RequestMapping("/newGoods")
    public String newGoods(Integer id, Model mode){
        Goods vo = new Goods();
        if (null != id) {
            vo.setId(id);
            List<Goods> list = goodsService.findGoodsList(vo);
            vo = list.get(0);
        }
        mode.addAttribute("form",vo);
        return "newGoods";
    }

    /**
     * 新增
     *
     * @param goods
     * @return
     */
    @RequestMapping("/addGoods")
    public String addGoods(Goods goods, RedirectAttributes redirectAttributes) {
        try {
            goodsService.insert(goods);
            redirectAttributes.addAttribute("msg", "success");
        } catch (Exception e) {
            redirectAttributes.addAttribute("msg", "failed");
        }
        return "redirect:goods";
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteGoodById")
    public String deleteGoodById(String id, RedirectAttributes redirectAttributes) {
        try {
            goodsService.deleteGoodById(id);
            redirectAttributes.addAttribute("msg", "success");
        } catch (Exception e) {
            redirectAttributes.addAttribute("msg", "failed");
        }
        return "redirect:goods";
    }

    @RequestMapping("/findGoodsList")
    @ResponseBody
    public List<Goods> findGoodsList(Goods goods) {
        List<Goods> list = goodsService.findGoodsList(goods);
        return list;
    }

}
